package com.GLM.Viewer.Circle;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.text.InputType;
import android.text.SpannableString;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.GLM.Constants.Constant;
import com.GLM.Tools.DB.DAO.UserInfoDAO;
import com.GLM.Tools.Utils.ViewsUtil;
import com.GLM.Tools.Utils.JSON.JSONResponse;
import com.GLM.Tools.Utils.JSON.JSONResponse.Status;
import com.GLM.Tools.Utils.JSON.JSONUtil;
import com.GLM.Viewer.R;

public class CreateNewCircleViewActivity extends Activity {
	View mInputFieldOneLine;
	TextView mInputFieldOneLineTextView;
	EditText mInputFieldOneLineEditText;

	View mInputFieldMoreLines;
	EditText mInputFieldMoreLinesEditText;

	Animation mAnimIn;
	Animation mAnimOut;
	private String mStep = "";

	Button mStep1Button;
	Button mStep2Button;
	Button mStep3Button;
	InputMethodManager imm;

	String mCircleName;
	String mCircleDescription;
	int[] UserIds;
	private static final int CREATE_DIALOG = 1;
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.view_circle_createnew);
		imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);

		initInputFields();

		initAnimation();

		initStep1Button();

		initStep2Button();

		initStep3Button();

		initRegisterInputFieldButton();
	}

	private void initInputFields() {
		mInputFieldOneLine = findViewById(R.id.inputfield_oneline);
		mInputFieldOneLine.setVisibility(View.GONE);
		mInputFieldOneLineTextView = (TextView) findViewById(R.id.inputfield_title);
		mInputFieldOneLineEditText = (EditText) findViewById(R.id.inputfield_edittext);
		mInputFieldOneLineTextView.setText(getString(R.string.forget_pwd_text));
		
		mInputFieldMoreLines = findViewById(R.id.inputfield_moreline);
		mInputFieldMoreLines.setVisibility(View.GONE);
		mInputFieldMoreLinesEditText = (EditText) findViewById(R.id.inputfieldmoreline_edittext);
	}

	private void initStep1Button() {
		mStep1Button = (Button) findViewById(R.id.newcirclebutton_step1);
		if (mCircleName != null) {
			initStep1ButtonAfterVerified();
		} else {
			initStep1ButtonBeforeVerified();
		}
	}

	private void initStep2Button() {
		mStep2Button = (Button) findViewById(R.id.newcirclebutton_step2);
		
		initStep2ButtonBeforeVerified();
		
	}

	private void initStep3Button() {
		mStep3Button = (Button) findViewById(R.id.newcirclebutton_step3);
		if (mCircleDescription != null) {
			initStep3ButtonAfterVerified();
		} else {
			initStep3ButtonBeforeVerified();
		}
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		outState.putString(Constant.REGISTER_DATA_USERNAME, mCircleName);
		outState.putString(Constant.REGISTER_DATA_NICKNAME, mCircleDescription);
	}

	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		super.onRestoreInstanceState(savedInstanceState);
		mCircleName = savedInstanceState.getString(Constant.REGISTER_DATA_USERNAME);
		mCircleDescription = savedInstanceState.getString(Constant.REGISTER_DATA_NICKNAME);
	}

	private void initRegisterInputFieldButton() {
		// one line
		Button inputCancelButton = (Button) findViewById(R.id.inputfield_cancelbutton);
		inputCancelButton.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				hideOneLineInputField();
			}
		});

		Button inputOkButton = (Button) findViewById(R.id.inputfield_okbutton);
		inputOkButton.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				handleRegisterInputFieldOkButtenEvent();

			}
		});
		// more liness
		Button inputMoreLineCancelButton = (Button) findViewById(R.id.inputfieldmoreline_cancelbutton);
		inputMoreLineCancelButton.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				hideMoreLinesInputField();
			}
		});

		Button inputMoreLineOkButton = (Button) findViewById(R.id.inputfieldmoreline_okbutton);
		inputMoreLineOkButton.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				handleRegisterInputFieldOkButtenEvent();

			}
		});
	}

	private void initAnimation() {
		mAnimIn = AnimationUtils.loadAnimation(this, R.anim.anim_register_in);
		mAnimOut = AnimationUtils.loadAnimation(this, R.anim.anim_register_out);
	}

	public void initBeginCreateDialog(){
		if(mCircleName != null && mCircleDescription != null && (UserIds !=null && UserIds.length>0)){
			showDialog(CREATE_DIALOG);
		}
	}
	
	private void initStep1ButtonBeforeVerified() {
		mStep1Button.setText(null);
		String line1 = getString(R.string.newcircle_unreg_step1_line1);
		String line2 = getString(R.string.newcircle_unreg_step1_line2);
		SpannableString spanText = ViewsUtil.getRegisterButtonSpannableString(line1, line2);
		mStep1Button.append(spanText);
	}

	private void initStep1ButtonAfterVerified() {
		mStep1Button.setText(null);
		String line2 = getString(R.string.newcircle_reg_step1_line2);
		SpannableString spanText = ViewsUtil.getRegisterButtonSpannableString(mCircleName, line2);
		mStep1Button.append(spanText);
	}

	private void initStep2ButtonBeforeVerified() {
		String line1 = getString(R.string.newcircle_unreg_step2_line1);
		String line2 = getString(R.string.newcircle_unreg_step2_line2);
		SpannableString spanText = ViewsUtil.getRegisterButtonSpannableString(line1, line2);
		mStep2Button.append(spanText);
	}

	

	private void initStep3ButtonBeforeVerified() {
		String line1 = getString(R.string.newcircle_unreg_step3_line1);
		String line2 = getString(R.string.newcircle_unreg_step3_line2);
		SpannableString spanText = ViewsUtil.getRegisterButtonSpannableString(line1, line2);
		mStep3Button.append(spanText);
	}

	private void initStep3ButtonAfterVerified() {
		mStep3Button.setText(null);
		String line1 = getString(R.string.newcircle_reg_step3_line1);
		SpannableString spanText = ViewsUtil.getRegisterButtonSpannableString(line1, mCircleDescription);
		mStep3Button.append(spanText);
	}

	protected void handleRegisterInputFieldOkButtenEvent() {
		if ("step1".equals(mStep)) {
			handleStep1RegisterInputFieldOkButtonEvent();
		} else if ("step3".equals(mStep)) {
			handleStep3IRegisterInputFieldOkButtonEvent();
		}
	}

	private void handleStep1RegisterInputFieldOkButtonEvent() {
		String circleName = mInputFieldOneLineEditText.getText().toString();
		if (circleName == null) {
			ViewsUtil.showErrorTip(this, R.string.registertip_input_tooshort);
			return;
		}
		if (circleName.length() > 30) {
			ViewsUtil.showErrorTip(this, R.string.registertip_input_toolong);
			return;
		}
		JSONObject jsonData = new JSONObject();
		JSONResponse jsonResponse = null;
		try {
			jsonData.put(Constant.PARAM_CIRCLE_NAME, circleName);
			jsonResponse = JSONUtil.postRequest(Constant.REQ_WAY_ISCIRCLENAMEUSED, jsonData);
		} catch (Exception e) {
			jsonResponse.setStatus(Status.ERR);
			e.printStackTrace();
		}
		if (jsonResponse.getStatus() == Status.ERR) {
			ViewsUtil.showErrorTip(this, R.string.global_error_networkerr);
			return;
		}
		JSONObject data = jsonResponse.getData();
		int status = -1;
		try {
			status = data.getInt(Constant.RESP_STATUS);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if (status == Constant.RESP_STATUS_CIRCLENAME_EXIST) {
			ViewsUtil.showErrorTip(this, R.string.newcircle_circlename_existed);
			return;
		}
		ViewsUtil.showErrorTip(this, R.string.newcircle_circlename_verified);
		mCircleName = circleName;
		initStep1ButtonAfterVerified();
		hideOneLineInputField();
		initBeginCreateDialog();
	}

	private void handleStep3IRegisterInputFieldOkButtonEvent() {
		mCircleDescription = mInputFieldMoreLinesEditText.getText().toString();
		initStep3ButtonAfterVerified();
		hideMoreLinesInputField();
		initBeginCreateDialog();
	}

	private void showOneLineInputField() {
		mInputFieldOneLine.startAnimation(mAnimIn);
		mInputFieldOneLine.setVisibility(View.VISIBLE);
		mInputFieldOneLineEditText.requestFocus();
		imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
	}

	private void showMoreLinesInputField() {
		mInputFieldMoreLines.startAnimation(mAnimIn);
		mInputFieldMoreLines.setVisibility(View.VISIBLE);
		mInputFieldMoreLinesEditText.requestFocus();
		imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
	}

	private void hideOneLineInputField() {
		mInputFieldOneLineEditText.setText("");
		mInputFieldOneLineEditText.setInputType(InputType.TYPE_NULL);
		mInputFieldOneLineEditText.clearFocus();
		mInputFieldOneLine.startAnimation(mAnimOut);
		mInputFieldOneLine.setVisibility(View.GONE);
		imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
	}

	private void hideMoreLinesInputField() {
		mInputFieldMoreLinesEditText.setText("");
		mInputFieldMoreLinesEditText.clearFocus();
		mInputFieldMoreLines.startAnimation(mAnimOut);
		mInputFieldMoreLines.setVisibility(View.GONE);
		imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
	}


	public void goBackButton_OnClick(View v) {
		mCircleName = null;
		mCircleDescription = null;
		NavUtils.navigateUpFromSameTask(this);
	}


	public void newCircleStep1Button_OnClick(View v) {
		mStep = "step1";
		mInputFieldOneLineTextView.setText(R.string.newcircle_inputfield_circlename);
		mInputFieldOneLineEditText.setInputType(InputType.TYPE_CLASS_TEXT);
		mInputFieldOneLineEditText.setHint(R.string.newcircle_inputfieldtip_circlename);
		if (mCircleName != null) {
			mInputFieldOneLineEditText.setText(mCircleName);
		}
		showOneLineInputField();
	}

	public void newCircleStep2Button_OnClick(View v) {
		mStep = "step2";
		Intent intent = new Intent(this, CreateNewCircleMyFriendsViewActivity.class);
		intent.putExtra("friendIds", UserIds);
		startActivityForResult(intent, 1);
	}

	public void newCircleStep3Button_OnClick(View v) {
		mStep = "step3";
		mInputFieldMoreLinesEditText.setInputType(InputType.TYPE_CLASS_TEXT);
		if (mCircleDescription != null) {
			mInputFieldMoreLinesEditText.setText(mCircleDescription);
		}
		showMoreLinesInputField();
		
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		if(resultCode == RESULT_OK){
			switch (requestCode) {
			case 1:
				Bundle bundle = data.getExtras();
				if(bundle != null){
					UserIds = bundle.getIntArray("chooseFriends");
					if(UserIds != null){
						int count = UserIds.length;
						String strLine1 = String.valueOf(count)+getString(R.string.person);
						String strLine2 = getString(R.string.newparty_tips_friend_choosed);
						mStep2Button.setText(ViewsUtil.getRegisterButtonSpannableString(strLine1, strLine2));
						for(int i=0; i<count; i++)
							Log.d("ids", UserIds[i]+"");
					}
				}
				initBeginCreateDialog();
				break;

			default:
				break;
			}
		}
	}

	
	
	@Override
	protected Dialog onCreateDialog(int id) {
		// TODO Auto-generated method stub
		AlertDialog.Builder builder = new AlertDialog.Builder(CreateNewCircleViewActivity.this);
		builder.setMessage(R.string.newcircle_reg_step_success);
		builder.setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() {
			
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				initCreateCircle();
			}
		});
		builder.setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
			
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				
			}
		});
		return builder.show();
		
	}

	public void initCreateCircle(){
		JSONObject jsonData = new JSONObject();
		JSONResponse jsonResponse = null;
		try {
			jsonData.put(Constant.PARAM_USERID_ONE , UserInfoDAO.getUserInfo(CreateNewCircleViewActivity.this).getUserId());
			jsonData.put("ring_introduce", mCircleDescription);
			jsonData.put("ring_name", mCircleName);
			JSONArray ja = new JSONArray();
			for(int i=0; i<UserIds.length; i++){
				ja.put(UserIds[i]);
			}
			
			jsonData.put("ring_user_list", ja);
			Log.d("jsonData", jsonData.toString());
			jsonResponse = JSONUtil.postRequest(Constant.REQ_WAY_CREATECIRCLE , jsonData);
			if(jsonResponse.getStatus() != Status.ERR){
				JSONObject data = jsonResponse.getData();
				int status = -1;
				status = data.getInt(Constant.RESP_STATUS);
				if(status == Constant.RESP_STATUS_SUCCESS){
					NavUtils.navigateUpTo(CreateNewCircleViewActivity.this, new Intent(CreateNewCircleViewActivity.this,CircleMainActivity.class));
					
					Toast.makeText(CreateNewCircleViewActivity.this, getString(R.string.newcircle_success), Toast.LENGTH_LONG).show();
				}
				
						
			}
		} catch (Exception e) {
			// TODO: handle exception
			
			e.printStackTrace();
		}
	}
}
